package znet

import (
	"errors"
	"fmt"
	"sync"
	"zinx/ziface"
)

type ConnManager struct {
	connections map[uint32]ziface.IConnection // 管理的链接集合
	connLock    sync.RWMutex                  // 保护链接集合的读写锁
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

// 添加链接
func (cm *ConnManager) Add(conn ziface.IConnection) {
	// 保护共享资源 加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	// 将conn 加入到集合
	cm.connections[conn.GetConnID()] = conn
	fmt.Println("connection add to ConnManager successfully: conn num = ", cm.Len())
}

// 删除链接
func (cm *ConnManager) Remove(conn ziface.IConnection) {
	// 保护共享资源，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	//删除当前链接
	delete(cm.connections, conn.GetConnID())
	fmt.Println("connID = ", conn.GetConnID(), " remove from ConnManager successfully: conn num = ", cm.Len())

}

// 根据connID 获取链接
func (cm *ConnManager) Get(connID uint32) (ziface.IConnection, error) {
	// 保护共享资源，读锁
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()

	// 获取Conn
	if conn, ok := cm.connections[connID]; ok {
		return conn, nil
	}

	return nil, errors.New("connection is not found!")

}

// 获取当前链接总数
func (cm *ConnManager) Len() int {
	return len(cm.connections)
}

// 清除并终止所有的链接
func (cm *ConnManager) ClearConn() {
	// 保护共享资源 加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	// 删除Conn将停止conn的工作
	for connId, conn := range cm.connections {
		// 停止
		conn.Stop()
		// 删除
		delete(cm.connections, connId)
	}
}
